package com.jl.obulibrary.driver;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;

import com.example.libpos.PsamLib;
import com.jxhc.rsudriver.model.PSAM_CHANNEL_res;
import com.xfkj.etcpos.core.driver.ILocalPsamDriver;
import com.xfkj.etcpos.core.exceps.CryptographyEngineException;



public class LocalPsamSerialDriver  implements ILocalPsamDriver {
    private boolean mStartOk = false;

    public byte getCurrentSock() {
        return CurrentSock;
    }

    public static void setCurrentSock(byte currentSock) {
        CurrentSock = currentSock;
    }

    //默认选择中卡槽1
    private static byte CurrentSock = PasmHead.ICC_SOCK_PSAM1;
    private String strSOCK[] = {"SOCK_PSAM1", "SOCK_PSAM5"};
    String strClock[] = {"ICC_CLOCK_1M", "ICC_CLOCK_2M", "ICC_CLOCK_3M", "ICC_CLOCK_4M", "ICC_CLOCK_6M", "ICC_CLOCK_12M", "NoUser"};

    /*
     * 参数 apduList为 指令个数   apduStr为指令 如 0500B0960006   其中05（16进制）为指令长度
     * data为每条apdu返回的结果连接，每条apdu返回结果的第一个字节为结果长度（16进制）
     * ps的RtnValue -1 则执行psam指令失败  返回 0 为正常   apdu
     */
    @Override
    public PSAM_CHANNEL_res psamChannel(int apduList, String apduStr) throws CryptographyEngineException {
        PSAM_CHANNEL_res ps = new PSAM_CHANNEL_res(0);
        ps.apduList = apduList;
        ps.data = "020000";     //
        Log.e("PSAM_TAG", "psamChannel >>> " + apduStr);
        byte[] Buff = new byte[1024];
//        byte[] len = new byte[1];
        int[] len = new int[1];
        byte[] sendData;
        int apduLeng = 0;
        int ret;
        int beginCount = 0;
        String apduItem, resultStr;
        for (int i = 0; i < apduList; i++) {
            apduLeng = Integer.parseInt(apduStr.substring(0, 2), 16);
            apduItem = apduStr.substring(2, apduLeng * 2 + 2);
            apduStr = apduStr.substring(apduLeng * 2 + 2);

            sendData = PasmHead.HexString2Bytes(apduItem);
            ret = PsamLib.APDU_Psam(CurrentSock, sendData, (byte) sendData.length, Buff, len);
            if (ret == 0) {
                resultStr = PasmHead.Bytes2HexString(Buff);

                if (resultStr.length() >= len[0] * 2) {
                    resultStr = resultStr.substring(0, len[0] * 2);
                }
                String char_length_hex = Integer.toHexString(resultStr.length() / 2);
                if (char_length_hex.length() % 2 == 1) {
                    char_length_hex = "0" + char_length_hex;
                }
                if (beginCount < 1) {
                    ps.data = "";
                    beginCount++;
                }
                ps.data += char_length_hex + resultStr;
            } else {
                ps.setRtnValue(-1);
                break;
            }
        }
        Log.e("PSAM_TAG", "psamChannel <<< " + ps);

        return ps;
    }

    //PSAM 复位
    @Override
    public void psamReset() {
        System.out.println("TODO 复位PSAM");
      byte len[] = new byte[1];
//        int[] len = new int[1];
        byte atr[] = new byte[512];
        new Thread() {
            @Override
            public void run() {

                super.run();
                String str;
                int ret;

                for (byte baud = PasmHead.ICC_BAUD_9600; baud <= PasmHead.ICC_BAUD_115200; baud++) {
                    ret = PsamLib.CardReset_Psam(CurrentSock, baud, atr, len);
                    if (ret == 0) {
                        str = String.format("Psam.CardReset_Psam [socket:%s] [strBaud:%s] [Clock:%s], ret=%d", strSOCK[CurrentSock], baud, strClock[3], ret);
                        Log.e("PSAM_TAG", str);

                        //卡槽复位成功
                        String displayData = PasmHead.Bytes2HexString(atr);
                        if (displayData.length() >= len[0] * 2) {
                            displayData = displayData.substring(0, len[0] * 2);
                        }
                        displayData = displayData.toUpperCase();
                        displayData = PasmHead.addSpaceForResult(displayData);
                        Log.e("PSAM_TAG", "psamReset: " + displayData);
                        break;
                    } else {
                        str = String.format("xxx Psam.CardReset_Psam [socket:%s] [strBaud:%s] [Clock:%s], ret=%d", strSOCK[CurrentSock], PasmHead.ICC_BAUD_115200, strClock[3], ret);
                        Log.e("PSAM_TAG", str);
                    }
                }
            }
        }.start();
    }

    //初始化PSAM
    public Boolean initPsamSlot(){
        System.out.println("TODO 这里初始化卡槽");
        int ret = PsamLib.Open_Psam();
        if (ret != 0)
        {
            mStartOk = false;
        }
        else {
            mStartOk = true;
        }
        return  mStartOk;
    }

    //PSAM
    public  String psamChannelApdu( String apduStr){
        byte[] Buff = new byte[1024];
//        byte[] len = new byte[1];
        int[] len = new int[1];

        byte[] sendData = PasmHead.HexString2Bytes(apduStr);
        int  ret = PsamLib.APDU_Psam(CurrentSock, sendData, (byte) sendData.length, Buff, len);
        String resultStr = PasmHead.Bytes2HexString(Buff);
//        Log.e("resultStr",resultStr);
        return resultStr.substring(0,len[0] * 2);

    }

    //关闭PSAM
    public  void psamClose( ){
        PsamLib.Close_Psam();
    }

    //获取PSAM 版本号
    public  String getPSAMVer(){
        return PsamLib.GetVer();
    }



}
